/*
 * @Author: imac
 * @Date:   2020-05-30 15:02:36
 * @Last Modified by:   Qinuoyun
 * @Last Modified time: 2020-07-20 13:13:37
 */

const apply = {
  namespaced: true,
  state: {
    is_login: false,
    menus: [],
    menus_status: false,
    userInfo: {},
    token: '',
    roles: ''

  },
  mutations: {
    login(state, provider) {
      if (provider) {
        console.log('获取用户信息', provider);
        state.is_login = true;
        state.token = provider.token;
        state.userInfo = provider;
      } else {
        state.token = '';
        state.is_login = false;
        state.userInfo = {};
      }
    },
    logout(state) {
      state.is_login = false;
      state.token = '';
      state.userInfo = {};
    },
    menus(state, routes) {
      state.menus = routes[0].children;
    },
    setMenusStatus(state, status) {
      state.menus_status = status;
    }
  },
  actions: {
    GetInfo({ commit }) {
      return new Promise(async (resolve, reject) => {
        try {
          let $cloud = this._vm.$cloud;
          let userInfo = $cloud.userInfo();
          // 用户权限信息
          let roleInfo = await $cloud.roles().menus(userInfo.role).then(res => {
            return res;
          }).catch(error => {
            // this._vm.$router.push('/');
            log('error', error);
          });
          // 配置信息
          let config = {
            parentKey: 'parentId',
            idKey: 'menuId',
            parentId: 0,
            childrenKey: 'children'
          };

          let basicsNav = [{
            'title': '后台管理',
            'path': '',
            'name': 'admin',
            'key': 'admin',
            'show': true,
            'icon': '',
            'children': []
          }];

          // 执行递归嵌套子集
          let childrenNav = $cloud
            .tree(config)
            .field('path', (value, self, parent) => {
              if (Object.keys(parent).length === 0) {
                return '/' + self['name'];
              } else {
                return parent['path'] + '/' + self['name'];
              }
            })
            .field('key', (value, self, parent) => {
              return self['name'];
            })
            .add('key', '')
            .on(roleInfo).get();
          // 合并数据
          basicsNav[0].children = childrenNav;
          // 设置菜单
          commit('menus', basicsNav);
          // 返回菜单信息
          resolve(basicsNav);
        } catch (error) {
          console.log('处理错误信息', error);
          // this._vm.$router.push('/');
        }
      });
    }
  }
};

export default apply;
